// File: adf_conv.cpp
// Author: Sergey Pershin <sergey dot pershin at hotmail dot com>

#include <stdio.h>
#include "progress_bar.h"

// Checking if a file exists.
bool isFileExists(const char *fileName)
{
    FILE *stream = fopen(fileName, "r");

    if (stream != NULL) {
        fclose(stream);
        return true;
    }

    return false;
}

// Get file size in bytes.
long int getFileSize(FILE *stream)
{
    long int fileSize;
    fseek(stream, 0, SEEK_END);
    fileSize = ftell(stream);
    fseek(stream, 0, SEEK_SET);
    return fileSize;
}

// Convert ADF to MP3 or MP3 to ADF.
void convert(const char *sourceFileName, const char *destinationFileName)
{
    FILE *sourceStream, *destinationStream;
    long int fileSize;
    ProgressBar *progressBar;
    char byte;

    if (sourceStream = fopen(sourceFileName, "rb")) {
        if (!isFileExists(destinationFileName)) {
            if (destinationStream = fopen(destinationFileName, "wb")) {
                fileSize = getFileSize(sourceStream);
                printf("File name: %s\n"
                    "Size: %d bytes\n\n", sourceFileName, fileSize);

                progressBar = new ProgressBar();
                progressBar->show();

                long int i = 0;
                while (!feof(sourceStream)) {
                    i++;

                    byte = getc(sourceStream);
                    byte = byte ^ 0x22;

                    if (!feof(sourceStream))
                        putc(byte, destinationStream);

                    progressBar->show(i, fileSize);
                }

                fclose(destinationStream);
                printf("\nDone!\n");
            } else {
                printf("Error: Cannot write destination file: '%s'.\n", destinationFileName);
            }
        } else {
            printf("Error: Destination file '%s' exists.\n", destinationFileName);
        }
        fclose(sourceStream);
    } else {
        printf("Error: Cannot open source file: '%s'.\n", sourceFileName);
    }
}

int main(int argc, const char *argv[])
{
    if (argc == 3) {
        convert(argv[1], argv[2]);
    } else {
        printf("Converter ADF (GTA Vice City) to MP3 and back.\n\n"
            "ADF2MP3 source destination\n");
    }
    return 0;
}
